package com.android.lovepick;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;

import com.android.lovepick.map.PathOverlay;
import com.android.lovepick.util.BaseUtils;
import com.android.lovepick.util.Constant;
import com.android.lovepick.util.PathInfo;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.MapActivity;
import com.baidu.mapapi.MapView;
import com.baidu.mapapi.Projection;

public class TestPathActivity extends MapActivity
{
	private final String TESTPATH_TAG = "TestPathActivity";
	private MainApp mApp = null;
	private MapView mMapView = null;
	private ArrayList<PathInfo> mPathInfos = null;

	@Override
	public void onCreate(Bundle bundle)
	{
		super.onCreate(bundle);
		setContentView(R.layout.test_path);

		mApp = (MainApp) this.getApplication();
		if (mApp.bmapMan == null)
		{
			mApp.bmapMan = new BMapManager(getApplication());
			mApp.bmapMan.init(MainApp.key, new MainApp.MyGeneraListener());
		}
		mApp.bmapMan.start();
		super.initMapActivity(mApp.bmapMan);
		initMap();
		mPathInfos = getPathInfos(Constant.jsonPath);
		if (mPathInfos != null)
		{
			Log.i(TESTPATH_TAG, "add pathoverlay to the map");
			Projection projection = mMapView.getProjection();
			PathOverlay overlay = new PathOverlay(projection, mPathInfos,
					Color.BLUE);
			mMapView.getOverlays().add(overlay);
			mMapView.invalidate();
		}
		else
		{
			BaseUtils.showToast(this, "pathinfos null!");
		}
	}

	private void initMap()
	{
		mMapView = (MapView) this.findViewById(R.id.test_map_view);
		mMapView.setBuiltInZoomControls(true);
		mMapView.setDrawOverlayWhenZooming(true);

	}

	private ArrayList<PathInfo> getPathInfos(String jsonPath)
	{
		ArrayList<PathInfo> pathInfos = new ArrayList<PathInfo>();
		try
		{
			JSONArray jsonArray = new JSONArray(jsonPath);
			for (int i = 0; i < jsonArray.length(); i++)
			{
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				PathInfo pathInfo = new PathInfo();
				pathInfo.setLatitude(jsonObject.getString("lat"));
				pathInfo.setLongitude(jsonObject.getString("lng"));
				pathInfos.add(pathInfo);
			}
			// Log.i(TESTPATH_TAG, "ArrayList<PathInfo>: " +
			// pathInfos.toString());
		}
		catch (JSONException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			pathInfos = null;
		}

		return pathInfos;
	}

	@Override
	protected boolean isRouteDisplayed()
	{
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	protected void onPause()
	{
		MainApp app = (MainApp) this.getApplication();
		if (app.bmapMan != null)
		{
			app.bmapMan.stop();
		}
		super.onPause();
	}

	@Override
	protected void onResume()
	{
		MainApp app = (MainApp) this.getApplication();
		app.bmapMan.start();
		super.onResume();
	}

}
